<template>
  <ul class="list">
    <li class="item"
        @click="handleLetterClick"
        v-for="(item,key) of letters"
        :key="key"
        :ref="item"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
    >{{item}}</li>
  </ul>
</template>
<script type="text/ecmascript-6">
export default{
  name:'CityAlphabet',
  props:['cities'],
  data:function(){
    return {
      touchStatus:false,
      startY:0,
      //做时间节流
      timer:null
    }
  },
  //数据发生更新并且页面完成渲染
  updated:function(){
    this.startY = this.$refs['A'][0].offsetTop
  },
  computed:{
    letters: function(){
      var letters = [];
//      得到一个['a','b'...]
      for(var city in this.cities){
        letters.push(city)
      }
      return letters;
    }
  },
  methods:{
    handleLetterClick:function(e){
      this.$emit('change', e.target.innerHTML);
    },
    //绑定手指滑动事件
    handleTouchStart:function(e){
      this.touchStatus = true;
    },
    handleTouchMove:function(e){
      if(this.touchStatus){
        //如果新的事件触发了就把上次存的事件给删了，这样就不会频繁出发了
        if(this.timer){
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(()=>{
          var touchY = e.touches[0].clientY - 79;
          var index = Math.floor((touchY - this.startY ) / 20);
          if(index >= 0 && index < this.letters.length){
            this.$emit('change', this.letters[index]);
          }
        },16)
      }
    },
    handleTouchEnd:function(){
      this.touchStatus = false;
    }
  }
}
</script>
<style lang="stylus" scoped>
@import "~styles/varibles.styl"
  .list
    position absolute;
    right:0;
    top:1.58rem;
    bottom:0;
    width:0.4rem;
    display flex;
    flex-direction column;
    justify-content center;
  .item
    text-align:center;
    line-height:0.4rem;
    color:$bgColor
</style>
